package com.basic.backend.utils;

import com.basic.backend.exception.BusinessException;
import com.basic.backend.model.dto.captcha.CaptchaInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component // 添加组件注解
@Slf4j
public class CaptchaGenerator {
    // 验证码字符集（去除了容易混淆的字符）
    private static final char[] CHARS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".toCharArray();
    private static final int CODE_LENGTH = 6;
    private static final int WIDTH = 160;
    private static final int HEIGHT = 50;
    private static final int LINE_COUNT = 6;

    private final RedisTemplate<String, Object> redisTemplate;

    // 通过构造器注入RedisTemplate
    @Autowired
    public CaptchaGenerator(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void generateCaptcha(String clientIP, HttpServletResponse response) throws IOException {
        // 生成随机验证码
        String code = generateRandomCode();

        // 存储到Redis（添加异常处理）
        try {
            CaptchaInfo captchaInfo = new CaptchaInfo(
                    code,
                    System.currentTimeMillis() + 5 * 60 * 1000,
                    0
            );
            redisTemplate.opsForValue().set(
                    "CAPTCHA:" + clientIP,
                    captchaInfo,
                    5,
                    TimeUnit.MINUTES
            );
            log.info("生成验证码: IP={}, Code={}", clientIP, code);
        } catch (Exception e) {
            throw new BusinessException("验证码存储失败", e);
        }

        // 生成图片
        BufferedImage image = createImage(code);

        // 输出图片流
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    private String generateRandomCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            sb.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return sb.toString();
    }

    private BufferedImage createImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景颜色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制验证码字符
        drawString(g, code);
        // 绘制干扰线
        drawNoise(g);

        g.dispose();
        return image;
    }

    private void drawString(Graphics2D g, String code) {
        g.setFont(new Font("Arial", Font.BOLD, 32));
        for (int i = 0; i < code.length(); i++) {
            g.setColor(new Color(
                    new Random().nextInt(150),
                    new Random().nextInt(150),
                    new Random().nextInt(150)));
            g.drawString(
                    String.valueOf(code.charAt(i)),
                    25 * i + 10,
                    HEIGHT / 2 + new Random().nextInt(HEIGHT / 2)
            );
        }
    }

    private void drawNoise(Graphics2D g) {
        Random random = new Random();
        for (int i = 0; i < LINE_COUNT; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g.setColor(new Color(
                    random.nextInt(200),
                    random.nextInt(200),
                    random.nextInt(200)));
            g.drawLine(x1, y1, x2, y2);
        }
    }
}